package com.scau.meetingbook.controller;

import com.alipay.api.internal.util.AlipaySignature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.scau.meetingbook.mapper.PaymentRecordMapper;
import com.scau.meetingbook.mapper.RoomReservationsMapper;
import com.scau.meetingbook.pojo.PaymentRecord;
import com.scau.meetingbook.pojo.RoomReservations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import com.alipay.api.internal.util.AlipaySignature;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;

@Controller
@RequestMapping("/alipay")
public class AliPayController {

    @Autowired
    private PaymentRecordMapper paymentRecordMapper;

    @Autowired
    private RoomReservationsMapper roomReservationsMapper;



    @PostMapping("/notify")
    public String handleAlipayNotify(HttpServletRequest request) {
        // 1. 验证通知合法性
//        if (!AlipaySignature.rsaCheckV1()) {
//            return "failure";
//        }

        // 2. 解析通知参数
        Map<String, String> params = parseRequestParams(request);
        String tradeStatus = params.get("trade_status");
        String outTradeNo = params.get("out_trade_no");

        // 3. 处理支付成功通知
        if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)) {
            updateReservationStatus(outTradeNo);
        }

        return "success";
    }

    @Transactional
    public void updateReservationStatus(String outTradeNo) {
        // 获取支付记录
        PaymentRecord record = paymentRecordMapper.selectOne(new QueryWrapper<PaymentRecord>().eq("out_trade_no", outTradeNo));

        if (record != null && "WAITING_PAY".equals(record.getStatus())) {
            // 获取预约记录
            RoomReservations reservation = roomReservationsMapper.selectById(record.getReservationId());

            // 更新预约状态
            if (reservation != null && "pending".equals(reservation.getReservationStatus())) {
                reservation.setReservationStatus("confirmed");
                roomReservationsMapper.updateById(reservation);

                // 更新支付记录状态
                record.setStatus("PAID");
                record.setPaymentTime(new Date());
                paymentRecordMapper.updateById(record);
            }
        }
    }

    private Map<String, String> parseRequestParams(HttpServletRequest request) {
        Map<String, String> params = new java.util.HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = iter.next();
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        return params;
    }


}